<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:xlink="http://www.w3.org/1999/xlink" xmlns:db="http://docbook.org/ns/docbook"
  xmlns:pbs="http://schema.pbs.gov.au" xmlns:g2g="http://schema.pbs.gov.au/Agency"
  xmlns:rwt="http://schema.pbs.gov.au/RWT/" xmlns:dct="http://purl.org/dc/terms/">

  <xsl:import href="common.xsl"/>

  <db:article>
    <db:info>
      <db:title>Link Extract File</db:title>

      <db:copyright>
        <db:year>2013</db:year>
        <db:year>2012</db:year>
        <db:year>2011</db:year>
        <db:year>2009</db:year>
        <db:holder>Commonwealth of Australia</db:holder>
      </db:copyright>

      <db:legalnotice>
        <db:para>This software is copyrighted by the Commonwealth of Australia ("The Commonwealth").
          The following terms apply to all files associated with the software unless explicitly
          disclaimed in individual files.</db:para>
        <db:para>Permission is hereby granted to use, copy, modify, distribute, and license this
          software and its documentation for any purpose, provided that existing copyright notices
          are retained in all copies and that this notice is included verbatim in any distributions.
          No written agreement, license, or royalty fee is required for any of the authorized uses.
          Modifications to this software may be copyrighted by their authors and need not follow the
          licensing terms described here, provided that the new terms are clearly indicated on the
          first page of each file where they apply.</db:para>
        <db:para>IN NO EVENT SHALL THE COMMONWEALTH OR DISTRIBUTORS BE LIABLE TO ANY PARTY FOR
          DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF
          THIS SOFTWARE, ITS DOCUMENTATION, OR ANY DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE
          BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.</db:para>
        <db:para>THE COMMONWEALTH SPECIFICALLY DISCLAIM ANY WARRANTIES, INCLUDING, BUT NOT LIMITED
          TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND
          NON-INFRINGEMENT. THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, AND THE COMMONWEALTH HAS
          NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
          MODIFICATIONS.</db:para>
      </db:legalnotice>

      <db:author>
        <db:personname>Steve Ball</db:personname>
        <db:email>Steve.Ball@health.gov.au</db:email>
        <db:affiliation>
          <db:orgname>Department of Health and Ageing</db:orgname>
          <db:orgdiv>PharmBiz</db:orgdiv>
        </db:affiliation>
      </db:author>

      <db:revhistory>
        <db:revision>
          <db:revnumber>3.6</db:revnumber>
          <db:date>2013-11-06</db:date>
          <db:authorinitials>SRB</db:authorinitials>
          <db:revremark>Use before and after restriction level to find all changed prescribing rules</db:revremark>
        </db:revision>
        <db:revision>
          <db:revnumber>3.5</db:revnumber>
          <db:date>2013-08-08</db:date>
          <db:authorinitials>SRB</db:authorinitials>
          <db:revremark>Check that the source document is appropriate</db:revremark>
        </db:revision>
        <db:revision>
          <db:revnumber>3.4</db:revnumber>
          <db:date>2013-07-29</db:date>
          <db:authorinitials>SRB</db:authorinitials>
          <db:revremark>Fixed note processing - find notes through circumstances</db:revremark>
        </db:revision>
        <db:revision>
          <db:revnumber>3.3</db:revnumber>
          <db:date>2013-07-16</db:date>
          <db:authorinitials>SRB</db:authorinitials>
          <db:revremark>Disregard deletions where the same restriction has been added with the same notes/cautions. Use codes to match, not @xml:id.</db:revremark>
        </db:revision>
        <db:revision>
          <db:revnumber>3.2</db:revnumber>
          <db:date>2013-07-05</db:date>
          <db:authorinitials>JPK</db:authorinitials>
          <db:revremark>Remove rwt:prescriber-instruction content from notes.</db:revremark>
        </db:revision>
        <db:revision>
          <db:revnumber>3.2</db:revnumber>
          <db:date>2012-11-09</db:date>
          <db:authorinitials>SRB</db:authorinitials>
          <db:revremark>Change priority of start date - restriction-reference is used first.</db:revremark>
        </db:revision>
        <db:revision>
          <db:revnumber>3.1.1</db:revnumber>
          <db:date>2012-11-07</db:date>
          <db:authorinitials>DMM</db:authorinitials>
          <db:revremark>Added documentation.</db:revremark>
        </db:revision>
        <db:revision>
          <db:revnumber>3.1</db:revnumber>
          <db:date>2012-11-01</db:date>
          <db:authorinitials>SRB</db:authorinitials>
          <db:revremark>Supply default non-effective date.</db:revremark>
        </db:revision>
        <db:revision>
          <db:revnumber>3.0</db:revnumber>
          <db:date>2012-08-29</db:date>
          <db:authorinitials>SRB</db:authorinitials>
          <db:revremark>Fix start and end dates.</db:revremark>
        </db:revision>
        <db:revision>
          <db:revnumber>2.7</db:revnumber>
          <db:date>2012-07-24</db:date>
          <db:authorinitials>DMM</db:authorinitials>
          <db:revremark>Fix bug where normalise-space() was being called instead of normalize-space()</db:revremark>
        </db:revision>
        <db:revision>
          <db:revnumber>2.6</db:revnumber>
          <db:date>2012-02-20</db:date>
          <db:authorinitials>SRB</db:authorinitials>
          <db:revremark>Upgraded to v2.7 schema.</db:revremark>
        </db:revision>
        <db:revision>
          <db:revnumber>2.5.1</db:revnumber>
          <db:date>2011-12-08</db:date>
          <db:authorinitials>SRB</db:authorinitials>
          <db:revremark>Fixed format for missing end date.</db:revremark>
        </db:revision>
        <db:revision>
          <db:revnumber>2.5</db:revnumber>
          <db:date>2011-11-24</db:date>
          <db:authorinitials>BD</db:authorinitials>
          <db:revremark>Only one row per prescribing-rule code</db:revremark>
        </db:revision>
        <db:revision>
          <db:revnumber>2.4</db:revnumber>
          <db:date>2011-11-23</db:date>
          <db:authorinitials>BD</db:authorinitials>
          <db:revremark>Update to handle 2.6 XML Markup for cautions</db:revremark>
        </db:revision>
        <db:revision>
          <db:revnumber>2.3</db:revnumber>
          <db:date>2011-11-14</db:date>
          <db:authorinitials>DMM</db:authorinitials>
          <db:revremark>Modified keys to address performance issues</db:revremark>
        </db:revision>
        <db:revision>
          <db:revnumber>2.2</db:revnumber>
          <db:date>2011-11-03</db:date>
          <db:authorinitials>SRB</db:authorinitials>
          <db:revremark>Remove leading and trailing spaces from note numbers before
            formatting</db:revremark>
        </db:revision>
        <db:revision>
          <db:revnumber>2.1</db:revnumber>
          <db:date>2011-10-31</db:date>
          <db:authorinitials>SRB</db:authorinitials>
          <db:revremark>Updated for PBS XML Schema v2.6.</db:revremark>
        </db:revision>
        <db:revision>
          <db:revnumber>2.0</db:revnumber>
          <db:date>2011-02-19</db:date>
          <db:authorinitials>SRB</db:authorinitials>
          <db:revremark>Updated for PBS XML Schema v2.4.</db:revremark>
        </db:revision>
        <db:revision>
          <db:revnumber>1.0</db:revnumber>
          <db:date>2009-10-02</db:date>
          <db:authorinitials>SRB</db:authorinitials>
          <db:revremark>Initial version.</db:revremark>
        </db:revision>
      </db:revhistory>
    </db:info>

    <db:para>This XSL stylesheet produces the Link ANS extract file (<db:filename>LinkExtract yyyymmdd.txt</db:filename>) from a PBS XML document.</db:para>
    <db:para>A restriction is comprised of one or more indications. The Link extract file file links the Indication Id to the PBS item code. Where there are multiple indications for an item, there will be multiple records in this file for that PBS item code.</db:para>
    <db:para>The source document must be the result of the <db:filename>delta.xsl</db:filename> XSL stylesheet.</db:para>
    <db:para>The result document is a text file.</db:para>
    <db:para>The field delimeter in this file is the tab character.</db:para>
    <db:table>
      <db:tgroup cols="5" align="left" colsep="1" rowsep="1">
        <db:colspec colnum="3" align="right"/>
        <db:colspec colnum="4" align="right"/>
        <db:thead>
          <db:row>
            <db:entry>Field Name</db:entry>
            <db:entry>Format</db:entry>
            <db:entry>Maximum Length</db:entry>
            <db:entry>Start Position</db:entry>
            <db:entry>Description</db:entry>
          </db:row>
        </db:thead>
        <db:tbody>
          <db:row>
            <db:entry>PBS Item Code</db:entry>
            <db:entry>Character</db:entry>
            <db:entry>6</db:entry>
            <db:entry>1</db:entry>
            <db:entry>five or six characters in format (n)nnnna</db:entry>
          </db:row>
          <db:row>
            <db:entry>Indication Id </db:entry>
            <db:entry>Character</db:entry>
            <db:entry>4</db:entry>
            <db:entry>7</db:entry>
            <db:entry>Numeric characters.The text of the Indication can be found in the RestrictionExtract file.</db:entry>
          </db:row>
          <db:row>
            <db:entry>Increased MQ/R Flag</db:entry>
            <db:entry>Character</db:entry>
            <db:entry>1</db:entry>
            <db:entry>12</db:entry>
            <db:entry>
              <db:para>Indicates whether the Indication  applies  to:</db:para>
              <db:simplelist>
                <db:member>increased quantities and/or repeats; or</db:member>
                <db:member>normal quantities and/or repeats; or</db:member>
                <db:member>both normal and increased quantities and/or repeats</db:member>
              </db:simplelist>
              <db:para>Values:</db:para>
              <db:simplelist>
                <db:member>1= this indication applies only to increased quantities and/or repeats</db:member>
                <db:member>this indication applies only to normal quantities  and/or repeats</db:member>
                <db:member>this indication applies both to normal and increased quantities and/or repeats</db:member>
              </db:simplelist>
              <db:para>For any given PBS item code, these flags will be either all 3 (the usual case), or all either 1 or 2.</db:para>
            </db:entry>
          </db:row>
          <db:row>
            <db:entry>Start date</db:entry>
            <db:entry>Character</db:entry>
            <db:entry>8</db:entry>
            <db:entry>14</db:entry>
            <db:entry>Format ddmmyyyy</db:entry>
          </db:row>
          <db:row>
            <db:entry>End date</db:entry>
            <db:entry>Character</db:entry>
            <db:entry>8</db:entry>
            <db:entry>23</db:entry>
            <db:entry>Format ddmmyyyy. Maybe blank if item is current (no end date has been set).</db:entry>
          </db:row>
          <db:row>
            <db:entry>Note Id</db:entry>
            <db:entry>Character</db:entry>
            <db:entry>4</db:entry>
            <db:entry>32</db:entry>
            <db:entry>the Note Id of any Note attached to the restriction</db:entry>
          </db:row>
          <db:row>
            <db:entry>Caution Id</db:entry>
            <db:entry>Character</db:entry>
            <db:entry>4</db:entry>
            <db:entry>37</db:entry>
            <db:entry>the Caution Id of any Caution attached to the restriction</db:entry>
          </db:row>
        </db:tbody>
      </db:tgroup>
    </db:table>
  </db:article>

  <xsl:output method="text"/>

  <db:param name="delimiter">
    <db:refpurpose>Field Delimiter</db:refpurpose>
    <db:para>Delimiter to use between fields. Default is tab character.</db:para>
  </db:param>
  <xsl:param name="delimiter" select="'&#x9;'"/>

  <db:param name="eol">
    <db:refpurpose>Record Delimiter</db:refpurpose>
    <db:para>Delimiter to use between records. Default is newline character.</db:para>
  </db:param>
  <xsl:param name="eol" select="'&#xa;'"/>

  <xsl:key name="ident" match="*" use="@xml:id"/>

  <db:template name="root">
    <db:refpurpose>Check Document Version</db:refpurpose>
    <db:para>Make sure that the source document uses the correct version of the PBS XML
      Schema.</db:para>
  </db:template>
  <xsl:template match="/">
    <xsl:variable name="major" select="substring-before(/*/@version, '.')"/>

    <xsl:choose>
      <xsl:when test="$major >= 2 and
        /pbs:root/pbs:schedule/pbs:listings-list/pbs:prescribing-rule/before">
        <xsl:apply-templates
          select="/pbs:root/pbs:schedule/pbs:listings-list/pbs:prescribing-rule[before/@type = 'restricted' or
                  after/@type = 'restricted' or
                  before/@type = 'authority-required' or
                  after/@type = 'authority-required' or
                  before/@type = 'streamlined' or
                  after/@type = 'streamlined']/*/*/rwt:restriction-references-list/rwt:restriction-reference"
        />
      </xsl:when>
      <xsl:when test="$major >= 2">
        <xsl:message terminate="yes">The source document must be processed using the delta.xsl stylesheet before using this stylesheet.</xsl:message>
      </xsl:when>
      <xsl:otherwise>
        <xsl:message terminate="yes">This stylesheet is designed to operate upon a Schedule XML
          document that conforms to version 2.8 (or later) of the PBS XML Schema. See
          http://dev.pbs.gov.au/ for more information on the PBS XML Schema, and for a version of
          this XSL stylesheet that operates on documents that conform to an earlier version of the
          schema.</xsl:message>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:template>

  <!-- This template is matched for both the before and current image -->
  <xsl:template match="rwt:restriction-reference">
    <xsl:choose>
      <xsl:when
        test="ancestor::after and
        ancestor::after/../before/*/rwt:restriction-references-list/rwt:restriction-reference[substring-before(@xlink:href, '-before') = current()/@xlink:href]">
        <xsl:variable name="after">
          <xsl:call-template name="make-record">
            <xsl:with-param name="compare" select="true()"/>
          </xsl:call-template>
        </xsl:variable>
        <xsl:variable name="before">
          <xsl:for-each
            select="ancestor::after/../before/*/rwt:restriction-references-list/rwt:restriction-reference[substring-before(@xlink:href, '-before') = current()/@xlink:href]">
            <xsl:call-template name="make-record">
              <xsl:with-param name="compare" select="true()"/>
            </xsl:call-template>
          </xsl:for-each>
        </xsl:variable>
        <xsl:choose>
          <xsl:when test="$before = $after">
            <xsl:call-template name="make-record">
              <xsl:with-param name="compare" select="false()"/>
            </xsl:call-template>
          </xsl:when>
          <xsl:otherwise>
            <xsl:call-template name="make-record">
              <xsl:with-param name="compare" select="false()"/>
            </xsl:call-template>
            <xsl:for-each
              select="ancestor::after/../before/*/rwt:restriction-references-list/rwt:restriction-reference[substring-before(@xlink:href, '-before') = current()/@xlink:href]">
              <xsl:call-template name="make-record">
                <xsl:with-param name="compare" select="false()"/>
                <xsl:with-param name="deleted" select="true()"/>
              </xsl:call-template>
            </xsl:for-each>
          </xsl:otherwise>
        </xsl:choose>
      </xsl:when>
      <xsl:when test="ancestor::after">
        <xsl:call-template name="make-record">
          <xsl:with-param name="compare" select="false()"/>
        </xsl:call-template>
      </xsl:when>
      <xsl:when
        test="ancestor::before/../after/*/rwt:restriction-references-list/rwt:restriction-reference[@xlink:href = substring-before(current()/@xlink:href, '-before')]"/>
      <xsl:otherwise>

        <!-- If same restriction is still listed, do note and caution codes match? If not then emit end-dated record -->
        
        <xsl:variable name="rstr.before" select="key('ident', substring(@xlink:href, 2))"/>
        <xsl:variable name="rstr.after"
          select="ancestor::before/../after/*/rwt:restriction-references-list/rwt:restriction-reference[key('ident', substring(@xlink:href, 2))/pbs:code = $rstr.before/pbs:code]"/>
        
        <xsl:variable name="before">
          <xsl:call-template name="make-record">
            <xsl:with-param name="compare" select="true()"/>
          </xsl:call-template>
        </xsl:variable>
        <xsl:variable name="after">
          <xsl:for-each
            select="$rstr.after">
            <xsl:call-template name="make-record">
              <xsl:with-param name="compare" select="true()"/>
            </xsl:call-template>
          </xsl:for-each>
        </xsl:variable>

        <xsl:if test="$before != $after">
          <xsl:call-template name="make-record">
            <xsl:with-param name="compare" select="false()"/>
            <xsl:with-param name="deleted" select="true()"/>
          </xsl:call-template>
        </xsl:if>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:template>

  <!-- current node is rwt:restriction-reference in prescribing rule (either before or after) -->
  <xsl:template name="make-record">
    <xsl:param name="compare" select="false()"/>
    <xsl:param name="deleted" select="false()"/>
    
    <!-- For Incr max qty/num rpts we need to know whether there are
           separate restrictions for normal amounts and increased amounts.
        -->

    <xsl:variable name="pr.normal">
      <xsl:apply-templates
        select="ancestor::rwt:restriction-references-list/rwt:restriction-reference"
        mode="pr-normal"/>
    </xsl:variable>
    <xsl:variable name="pr.increases">
      <xsl:apply-templates
        select="ancestor::rwt:restriction-references-list/rwt:restriction-reference"
        mode="pr-increases"/>
    </xsl:variable>
    <xsl:variable name="flag">
      <xsl:call-template name="distinct">
        <xsl:with-param name="list1" select="normalize-space($pr.normal)"/>
        <xsl:with-param name="list2" select="normalize-space($pr.increases)"/>
      </xsl:call-template>
    </xsl:variable>

    <xsl:apply-templates select="key('ident', substring(@xlink:href, 2))">
      <xsl:with-param name="flag" select="$flag"/>
      <xsl:with-param name="parent" select="ancestor::before|ancestor::after"/>
      <xsl:with-param name="ref" select="."/>
      <xsl:with-param name="compare" select="$compare"/>
      <xsl:with-param name="deleted" select="$deleted"/>
    </xsl:apply-templates>
  </xsl:template>

  <xsl:template match="rwt:restriction-reference" mode="pr-normal">
    <xsl:apply-templates select="key('ident', substring(@xlink:href, 2))" mode="pr-normal"/>
  </xsl:template>
  <xsl:template match="rwt:restriction" mode="pr-normal">
    <xsl:variable name="am.normal">
      <xsl:apply-templates select="rwt:circumstance|rwt:circumstance-reference" mode="am-normal"/>
    </xsl:variable>
    <xsl:variable name="am.increases">
      <xsl:apply-templates select="rwt:circumstance|rwt:circumstance-reference" mode="am-increases"
      />
    </xsl:variable>

    <xsl:if
      test="normalize-space($am.normal) != '' and
                  normalize-space($am.increases) = ''">
      <xsl:value-of select="@xml:id"/>
      <xsl:text> </xsl:text>
    </xsl:if>
  </xsl:template>
  <xsl:template match="rwt:restriction-reference" mode="pr-increases">
    <xsl:apply-templates select="key('ident', substring(@xlink:href, 2))" mode="pr-increases"/>
  </xsl:template>
  <xsl:template match="rwt:restriction" mode="pr-increases">
    <xsl:variable name="am.normal">
      <xsl:apply-templates select="rwt:circumstance|rwt:circumstance-reference" mode="am-normal"/>
    </xsl:variable>
    <xsl:variable name="am.increases">
      <xsl:apply-templates select="rwt:circumstance|rwt:circumstance-reference" mode="am-increases"
      />
    </xsl:variable>

    <xsl:if
      test="normalize-space($am.increases) != '' and
                  normalize-space($am.normal) = ''">
      <xsl:value-of select="@xml:id"/>
      <xsl:text> </xsl:text>
    </xsl:if>
  </xsl:template>

  <xsl:template match="rwt:circumstance" mode="am-normal">
    <xsl:if test="not(starts-with(rwt:authority-method, 'auth:increase'))">
      <xsl:text> </xsl:text>
      <xsl:value-of select="rwt:authority-method"/>
    </xsl:if>
  </xsl:template>
  <xsl:template match="rwt:circumstance-reference" mode="am-normal">
    <xsl:apply-templates select="key('ident', substring(@xlink:href, 2))" mode="am-normal"/>
  </xsl:template>
  <xsl:template match="rwt:circumstance" mode="am-increases">
    <xsl:if
      test="(rwt:authority-method = 'auth:increase-maximum-quantity' and
                  rwt:increase/g2g:eauthority > 1) or
      (rwt:authority-method = 'auth:increase-number-repeats' and
                  rwt:increase/g2g:eauthority > 0)">
      <xsl:text> </xsl:text>
      <xsl:value-of select="rwt:authority-method"/>
    </xsl:if>
  </xsl:template>
  <xsl:template match="rwt:circumstance-reference" mode="am-increases">
    <xsl:apply-templates select="key('ident', substring(@xlink:href, 2))" mode="am-increases"/>
  </xsl:template>

  <xsl:template match="rwt:restriction">
    <xsl:param name="parent" select="/.."/>
    <xsl:param name="ref" select="/.."/>
    <xsl:param name="flag" select="0"/>
    <xsl:param name="compare" select="false()"/> <!-- whether record is being generated for comparison purposes: do not include dates if it is -->
    <xsl:param name="deleted" select="false()"/> <!-- whether deletion record is being created -->

    <xsl:variable name="am.normal">
      <xsl:apply-templates select="rwt:circumstance|rwt:circumstance-reference" mode="am-normal"/>
    </xsl:variable>
    <xsl:variable name="am.increases">
      <xsl:apply-templates select="rwt:circumstance|rwt:circumstance-reference" mode="am-increases"
      />
    </xsl:variable>

    <xsl:if
      test="normalize-space($am.normal) != '' and
                  not(contains($am.normal, 'auth:none'))">
      <xsl:call-template name="pad-right">
        <xsl:with-param name="text" select="$parent/pbs:code"/>
        <xsl:with-param name="length" select="5"/>
      </xsl:call-template>
      <xsl:value-of select="$delimiter"/>
      <xsl:call-template name="pad-right">
        <xsl:with-param name="text">
          <xsl:apply-templates select="pbs:code" mode="textonly"/>
        </xsl:with-param>
        <xsl:with-param name="length" select="4"/>
      </xsl:call-template>
      <xsl:value-of select="$delimiter"/>
      <!-- Increased max qty/num rpts flag -->
      <xsl:choose>
        <xsl:when test="number($flag) = 0">3</xsl:when>
        <xsl:when
          test="normalize-space($am.normal) = '' and
                        normalize-space($am.increases) != ''"
          >1</xsl:when>
        <xsl:when
          test="normalize-space($am.normal) != '' and
                        normalize-space($am.increases) = ''"
          >2</xsl:when>
        <xsl:otherwise>
          <!-- This should never happen -->
          <xsl:text>0</xsl:text>
        </xsl:otherwise>
      </xsl:choose>
      <xsl:value-of select="$delimiter"/>
      <!-- Start Date -->
      <!-- Need to select the latest date of:
           pr-restriction reference
           restriction
           prescriber-instruction
           administrative-advice
           caution
        -->
      <xsl:variable name="date.start">
        <xsl:call-template name="find-latest">
          <xsl:with-param name="dates">
            <xsl:value-of select="$parent/pbs:effectivity/pbs:start"/>
            <xsl:text> </xsl:text>
            <xsl:value-of select="$ref/pbs:effectivity/pbs:start"/>
            <xsl:apply-templates select=".|*" mode="note-start"/>
          </xsl:with-param>
        </xsl:call-template>
      </xsl:variable>
      <xsl:choose>
        <xsl:when test="$compare">
          <xsl:text>        </xsl:text>
        </xsl:when>
        <xsl:when test="$ref/pbs:effectivity/pbs:start">
          <xsl:call-template name="format-date">
            <xsl:with-param name="date" select="$ref/pbs:effectivity/pbs:start"/>
          </xsl:call-template>
        </xsl:when>
        <xsl:when test="$date.start != '' and
          $date.start != '0'">
          <xsl:call-template name="format-date">
            <xsl:with-param name="date" select="$date.start"/>
          </xsl:call-template>
        </xsl:when>
        <xsl:otherwise>
          <xsl:text>        </xsl:text>
        </xsl:otherwise>
      </xsl:choose>
      <xsl:value-of select="$delimiter"/>
      <!-- End Date -->
      <xsl:variable name="date.end">
        <xsl:call-template name="find-latest">
          <xsl:with-param name="dates">
            <xsl:value-of select="$parent/pbs:effectivity/pbs:non-effective"/>
            <xsl:text> </xsl:text>
            <xsl:value-of select="$ref/pbs:effectivity/pbs:non-effective"/>
            <xsl:apply-templates select=".|*" mode="note-end"/>
          </xsl:with-param>
          <xsl:with-param name="default" select="'0'"/>
        </xsl:call-template>
      </xsl:variable>
      <xsl:choose>
        <xsl:when test="$deleted">
          <xsl:call-template name="format-date-minus-1D">
            <xsl:with-param name="date" select="/pbs:root/pbs:info/dct:valid"/>
          </xsl:call-template>
        </xsl:when>
        <xsl:when test="$compare or $date.end = '0'">
          <xsl:text>        </xsl:text>
        </xsl:when>
        <xsl:when test="$date.end">
          <xsl:call-template name="format-date-minus-1D">
            <xsl:with-param name="date" select="$date.end"/>
          </xsl:call-template>
        </xsl:when>
        <xsl:otherwise>
          <xsl:text>        </xsl:text>
        </xsl:otherwise>
      </xsl:choose>
      <xsl:value-of select="$delimiter"/>
      <!-- Note -->
      <xsl:variable name="note.raw">
        <xsl:apply-templates
          select="rwt:circumstance |
          rwt:circumstance-reference |
          rwt:definition |
          rwt:definition-reference |
                                     rwt:administrative-advice |
                                     rwt:administrative-advice-reference"
          mode="note"/>
      </xsl:variable>
      <!-- remove any leading and trailing spaces from the note number before formatting -->
      <xsl:variable name="note" select="normalize-space($note.raw)"/>
      <xsl:choose>
        <xsl:when test="$note != ''">
          <xsl:call-template name="pad-number">
            <xsl:with-param name="number">
              <xsl:choose>
                <xsl:when test="contains($note, ' ')">
                  <xsl:value-of select="substring-before($note, ' ')"/>
                </xsl:when>
                <xsl:otherwise>
                  <xsl:value-of select="$note"/>
                </xsl:otherwise>
              </xsl:choose>
            </xsl:with-param>
            <xsl:with-param name="length" select="4"/>
            <xsl:with-param name="pad" select="'0'"/>
          </xsl:call-template>
        </xsl:when>
        <xsl:otherwise>
          <xsl:text>0000</xsl:text>
        </xsl:otherwise>
      </xsl:choose>
      <xsl:value-of select="$delimiter"/>
      <!-- Caution -->
      <xsl:variable name="caution">
        <xsl:apply-templates
          select="rwt:circumstance |
                                     rwt:circumstance-reference |
                                     rwt:caution |
                                     rwt:caution-reference"
          mode="caution"/>
      </xsl:variable>
      <xsl:choose>
        <xsl:when test="$caution != ''">
          <xsl:call-template name="pad-number">
            <xsl:with-param name="number">
              <xsl:choose>
                <xsl:when test="contains($caution, ' ')">
                  <xsl:value-of select="substring-before($caution, ' ')"/>
                </xsl:when>
                <xsl:otherwise>
                  <xsl:value-of select="$caution"/>
                </xsl:otherwise>
              </xsl:choose>
            </xsl:with-param>
            <xsl:with-param name="length" select="4"/>
            <xsl:with-param name="pad" select="'0'"/>
          </xsl:call-template>
        </xsl:when>
        <xsl:otherwise>
          <xsl:text>0000</xsl:text>
        </xsl:otherwise>
      </xsl:choose>
      <xsl:value-of select="$eol"/>
    </xsl:if>
  </xsl:template>

  <xsl:template
    match="rwt:circumstance-reference |
    rwt:definition-reference |
                       rwt:administrative-advice-reference"
    mode="note">
    <xsl:apply-templates select="key('ident', substring(@xlink:href, 2))" mode="note"/>
  </xsl:template>
  <xsl:template match="rwt:circumstance-reference |
                       rwt:caution-reference"
    mode="caution">
    <xsl:apply-templates select="key('ident', substring(@xlink:href, 2))" mode="caution"/>
  </xsl:template>

  <xsl:template
    match="rwt:definition |
                       rwt:administrative-advice"
    mode="note">
    <xsl:value-of select="pbs:code"/>
    <xsl:text> </xsl:text>
  </xsl:template>

  <xsl:template match="rwt:circumstance" mode="note">
      <xsl:apply-templates
          select="rwt:administrative-advice |
                  rwt:administrative-advice-reference"
          mode="note"/>
  </xsl:template>

  <xsl:template match="rwt:circumstance" mode="caution">
    <xsl:apply-templates select="rwt:caution |
      rwt:caution-reference" mode="caution"/>
  </xsl:template>

  <xsl:template match="rwt:caution" mode="caution">
    <xsl:value-of select="pbs:code"/>
    <xsl:text> </xsl:text>
  </xsl:template>

  <xsl:template match="text()"/>
  <xsl:template match="text()" mode="note"/>
  <xsl:template match="text()" mode="caution"/>

  <xsl:template name="distinct">
    <xsl:param name="list1"/>
    <xsl:param name="list2"/>

    <xsl:choose>
      <xsl:when test="not($list1) and not($list2)">0</xsl:when>
      <xsl:when test="not($list1)">0</xsl:when>
      <xsl:when test="not($list2)">0</xsl:when>

      <xsl:otherwise>
        <xsl:call-template name="distinct-aux">
          <xsl:with-param name="list1" select="$list1"/>
          <xsl:with-param name="list2" select="$list2"/>
        </xsl:call-template>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:template>
  <xsl:template name="distinct-aux">
    <xsl:param name="list1"/>
    <xsl:param name="list2"/>

    <xsl:variable name="first" select="substring-before($list1, ' ')"/>

    <xsl:choose>
      <xsl:when test="not($list1)">1</xsl:when>
      <xsl:when test="not($list2)">1</xsl:when>
      <xsl:when test="contains($list2, $first)">0</xsl:when>
      <xsl:otherwise>
        <xsl:call-template name="distinct">
          <xsl:with-param name="list1" select="substring-after($list1, ' ')"/>
          <xsl:with-param name="list2" select="$list2"/>
        </xsl:call-template>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:template>
</xsl:stylesheet>
